package com.yusp75.myexam.ui.exam

import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.yusp75.myexam.com.yusp75.myexam.data.AnswerResultMap
import com.yusp75.myexam.databinding.ItemQuestionResultBinding


class ExamResultAdapter(
    private val onClick: (AnswerResultMap) -> Unit
) : ListAdapter<AnswerResultMap, ExamResultAdapter.ViewHolder>(QuestionDiffCallback()) {

    inner class ViewHolder(val binding: ItemQuestionResultBinding) :
        RecyclerView.ViewHolder(binding.root)

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val binding = ItemQuestionResultBinding.inflate(
            LayoutInflater.from(parent.context), parent, false
        )
        return ViewHolder(binding)
    }

    @SuppressLint("SetTextI18n")
    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val item = getItem(position)
        holder.binding.apply {
            tvContent.text = "${item.idx}. ${item.content}"
            correctText.text = "答案：${item.correctAnswer}"
            errorText.text = "回答：${item.userAnswer}"
            // 解析是否空
            tvAnalysis.apply {
                visibility = if (item.analysis.isNullOrBlank()) View.GONE else View.VISIBLE
                text = item.analysis?.takeUnless { it.isBlank() }?.let { "解析：$it" } ?: ""
            }
            root.setOnClickListener { onClick(item) }
        }

        // 强制重新测量高度
        holder.itemView.post {
            holder.itemView.requestLayout()
        }
    }

    class QuestionDiffCallback : DiffUtil.ItemCallback<AnswerResultMap>() {
        override fun areItemsTheSame(oldItem: AnswerResultMap, newItem: AnswerResultMap) =
            oldItem.idx == newItem.idx

        override fun areContentsTheSame(oldItem: AnswerResultMap, newItem: AnswerResultMap) =
            oldItem == newItem
    }
}

